package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.media.dto.ChannelDto;
import com.heima.media.entity.WmChannel;
import com.heima.media.mapper.WmChannelMapper;
import com.heima.media.service.IWmChannelService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.xmlunit.util.Linqy;

import java.util.List;

/**
 * @author: itheima
 * @create: 2022-06-28 14:42
 */
@Service
public class WmChannelServiceImpl extends ServiceImpl<WmChannelMapper, WmChannel> implements IWmChannelService {


    /**
     * 频道分页条件查询
     *
     * @param dto
     * @return ResponseResult:统一响应对象   子类：PageResponseResult 分页响应对象
     */
    @Override
    public ResponseResult queryByPage(ChannelDto dto) {
        //1.构建分页对象 Page
        IPage<WmChannel> page = new Page<>(dto.getPage(), dto.getSize());

        //2.构建查询条件
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getName())) {
            queryWrapper.like(WmChannel::getName, dto.getName());
        }

        //3.调用业务层执行分页方法
        page = this.page(page, queryWrapper);

        //4.封装分页响应结果
        PageResponseResult responseResult = new PageResponseResult<>(dto.getPage(), dto.getSize(), page.getTotal(), page.getRecords());
        return responseResult;
    }


    /**
     * 保存频道
     *
     * @param wmChannel
     */
    @Override
    public void saveChannel(WmChannel wmChannel) {
        //1.根据频道名称查询是否存在
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getName, wmChannel.getName());
        int count = this.count(queryWrapper);
        if (count == 0) {
            //1.设置属性值
            wmChannel.setIsDefault(false);
            wmChannel.setStatus(false);
            wmChannel.setOrd(0);
            //2.执行保存
            this.save(wmChannel);
        } else {
            throw new RuntimeException("数据以及存在！");
        }
    }

    @Override
    public ResponseResult queryByList() {
        LambdaQueryWrapper<WmChannel> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WmChannel::getStatus, 1);
        List<WmChannel> list = this.list(queryWrapper);
        return ResponseResult.okResult(list);
    }
}
